package com.tanhua.dubbo.server.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Author YuShiLong
 * @Date 2021/4/21 18:42
 * @Version 1.0
 */

/**
 * 原理:使用redis的自增长类型,来实现自增长id
 */
@Service
public class IdService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 生成自增长的id
     *
     * @return
     */
    public Long createdId(String type, String objectId) {

        type = StringUtils.upperCase(type);

        String hashKey = "TANHUA_ID_HASH_" + type;

        //如果objectId已经存在的话,就返回对应的id
        if (redisTemplate.opsForHash().hasKey(hashKey, objectId)) {
            return Long.valueOf(redisTemplate.opsForHash().get(hashKey, objectId).toString());
        }


        String key = "TANHUA_ID_" + type;

        //调用redis提供的自增长方法
        Long id = redisTemplate.opsForValue().increment(key);

        //将生成的id写入到hash表中
        redisTemplate.opsForHash().put(hashKey, objectId, id.toString());

        return id;
    }
}
